package com.olive.config;

import org.springframework.security.authentication.ReactiveAuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;

import com.olive.model.JwtAuthenticationToken;

import reactor.core.publisher.Mono;

@Component
public class CustomAuthenticationManager implements ReactiveAuthenticationManager {

	@Override
	public Mono<Authentication> authenticate(Authentication authentication) {
		JwtAuthenticationToken jwtAuthenticationToken = null;
		if (authentication instanceof JwtAuthenticationToken) {
			jwtAuthenticationToken = (JwtAuthenticationToken) authentication;
		} else {
			throw new CustomAccessDeniedException(100, "authenticate fail");
		}
		String token = jwtAuthenticationToken.getToken();
		if (!StringUtils.hasText(token)) {
			throw new CustomAccessDeniedException(100, "token is null, not auth");
		}
		jwtAuthenticationToken.setUserId("admin");
		// TODO 解析 token 获取登录信息

		authentication.setAuthenticated(true);
		return Mono.just(authentication);
	}

	public ServerWebExchange onSuccess(Authentication authentication, ServerWebExchange serverWebExchange) {
		return serverWebExchange;
	}

}